#### LAB 5 ####

###Problem 1

#create abundance vector
lynx = c(269, 321, 585, 871, 1475, 2821, 3928, 5943, 4950, 2577, 523, 98, 184, 279, 409, 2285, 2685, 3409, 1824, 409, 151, 45, 68, 213, 546, 1033, 2129, 2536, 957, 361, 377, 225, 360, 731, 1638, 2725, 2871, 2119, 684, 299, 236, 245, 552, 1623, 3311, 6721, 4254, 687, 255, 473, 358, 784, 1594, 1676, 2251, 1426, 756, 299, 201, 229, 469, 736, 2042, 2811, 4431, 2511, 389, 73, 39, 49, 59, 188, 377, 1292, 4031, 3495, 587, 105, 153, 387, 758, 1307, 3465, 6991, 6313, 3794, 1836, 345, 382, 808, 1388, 2713, 3800, 3091, 2985, 3790, 674, 81, 80, 108, 229, 399, 1132, 2432, 3574, 2935, 1537, 529, 485, 662, 1000, 1590,2657, 3396)

# a.) plot lynx data
plot(years,lynx, xlab="year", ylab="abundance", type="b")


# b.) Autocorrelation to estimate period
#	note the carry over and carry though values.  Look at the "peaks" and "troughs"

acf(lynx)

# c.) Periodogram
#

spectrum(lynx)
prgm <- spectrum(lynx, plot=FALSE)
plot(prgm$freq,prgm$spec, xlab="frequency, bandwidth = 0.00241", ylab="amplitude",type="l")


### Problem 2

# b.) null
nullprgm <- spectrum(sample(lynx), plot=FALSE)
plot(nullprgm$freq,nullprgm$spec,ylim=c(0,4e+07), xlab="frequency, bandwidth = 0.00241", ylab="amplitude",type="l")


# c.)
plot(prgm$freq,prgm$spec, xlab="frequency, bandwidth = 0.00241", ylab="amplitude",type="l")
for(i in 1:500)
{
	points(prgm$freq, spectrum(sample(lynx), plot=FALSE)$spec)
}
#spectrum(sample(lynx))


### Problem 3
# note that a = log(R), b1 = 1-c1, b2 = -c2


# a
x = log(lynx)
  x.now  =  x[3:114]

  x.1  =  x[2:113]

  x.2  =  x[1:112]

lm(x.now ~ x.1 + x.2)

# b
 xl = log(sample(lynx))
 xl.now = xl[3:114]
 xl.1 = xl[2:113]
 xl.2 = xl[1:112]

lm (xl.now ~ xl.1 + xl.2)
